package com.lz.ionicbase;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.Uri;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.Toast;

import com.lz.ionicbase.ui.activity.WelcomeActivity;
import com.lz.ionicbase.utils.Constant;
import com.lz.ionicbase.utils.NetStateUtils;
import com.lz.ionicbase.utils.SpUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cookie.store.CookieStore;
import com.lzy.okgo.cookie.store.MemoryCookieStore;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;

import okhttp3.Cookie;
import okhttp3.HttpUrl;


/**
 * 全局Application
 */
public class SuperApp extends Application {

    private static final String TAG = "SuperApp";

    private static SuperApp context;

    public static SuperApp getContext() {
        return context;
    }


    /**
     * 语言设置
     * Map<String, Object[]>
     *     String       设置界面显示的语言
     *     Object[0]    对应的接口参数
     *     Object[1]    对应的Locale对象
     */
    public static Map<String, Object[]> lanMap = new HashMap<String, Object[]>();
    {
        lanMap.put("简体中文", new Object[]{"zh",Locale.SIMPLIFIED_CHINESE});
        lanMap.put("English", new Object[]{"en",Locale.ENGLISH});
    }

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;

        isReStartAfterCrash();
        initOkHttpUtil();
//        initBugly();

        SuperAppException.getInstance().init(this);

        selectIPfromSSID();
        setLanguage();
    }

    public void setLanguage() {
        String lan  = SpUtils.getString(getApplicationContext(), SpUtils.KEY_LANGUAGE,"简体中文");

        Resources resources = getApplicationContext().getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        Configuration config = resources.getConfiguration();
        // 应用用户选择语言
        config.locale = (Locale) lanMap.get(lan)[1];
        resources.updateConfiguration(config, dm);
    }

    private void selectIPfromSSID() {
        int type = NetStateUtils.getConnectedType(this);
        //网络类型为WIFI的时候,记住此时的WIFI对应的IP
        if(type == 1){
            String ssid = NetStateUtils.getWIFISSID(this);
            if(!TextUtils.isEmpty(ssid)){
                //从SSID中选择曾经连接的IP
//                String baseUrl = "http://"+serverip+":"+port;
                String baseUrl = SpUtils.getString(this,ssid, "");
                if(!TextUtils.isEmpty(baseUrl)){
                    String host = Uri.parse(baseUrl).getHost();
                    int port = Uri.parse(baseUrl).getPort();
                    SpUtils.saveString(this, Constant.SERVERIP,host);
                    SpUtils.saveString(this, Constant.PORT,port+"");
                    SpUtils.saveString(this, SpUtils.KEY_BASE_URL, baseUrl);
                }
            }
        }
    }

    public void setCurrWifiIP(){
        int type = NetStateUtils.getConnectedType(this);
        //网络类型为WIFI的时候,记住此时的WIFI对应的IP
        if(type == 1){
            String ssid = NetStateUtils.getWIFISSID(this);
            Log.e(TAG, "ssid = " + ssid);
            if(!TextUtils.isEmpty(ssid)){
                String serverip = SpUtils.getString(this, Constant.SERVERIP,"");
                String port = SpUtils.getString(this, Constant.PORT,"");
                String baseUrl = "http://"+serverip+":"+port;
                SpUtils.saveString(this,ssid, baseUrl);
            }
        }
    }

    /**
     * 由于崩溃时，回退栈依然存在，此时如果有静态数据会发生连续崩溃。
     * 解决方案：记录崩溃标记，在SuperApplication中以单实例方式启动栈底activity，清空回退栈。
     */
    private void isReStartAfterCrash() {
        boolean bRestartAfterCrash = SpUtils.getBoolean(this,SpUtils.KEY_APP_CRASHED,false);
        if (bRestartAfterCrash) {
            // Clear crash flag.
            SpUtils.saveBoolean(this,SpUtils.KEY_APP_CRASHED,false);
            // Re-launch from root activity with cleared stack.
            Intent intent = new Intent(this, WelcomeActivity.class );
            intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK );
            startActivity( intent );
        }
    }

    private void initBugly() {
//        CrashReport.initCrashReport(getApplicationContext(), "009f320157", true);

//        Bugly.init(getApplicationContext(), "009f320157", false);
//        Beta.autoCheckUpgrade = false;//是否自动检查更新
//        Beta.storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    }


    private void initOkHttpUtil() {
        OkGo.init(this);
        OkGo.getInstance()
                .debug("OkGo", Level.WARNING, true)
                .setCookieStore(new MemoryCookieStore())            //cookie使用内存缓存（app退出后，cookie消失）
//                .setCookieStore(new PersistentCookieStore())        //cookie持久化存储，如果cookie不过期，则一直有效
                .setConnectTimeout(15000)
                .setWriteTimeOut(15000)
                .setReadTimeOut(15000)
//                .setCacheMode(CacheMode.DEFAULT)
//                .setCacheMode(CacheMode.IF_NONE_CACHE_REQUEST)
//                .setCacheTime(1000*60*2)//缓存过期时间两分钟

                .setRetryCount(0);
    }

    /**
     * 返回当前程序版本名
     */
    public static String getAppVersionName(Context context) {
        String versionName = "1.0.0";
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
            if (versionName == null || versionName.length() <= 0) {
                return "1.0.0";
            }
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versionName;
    }




    /**
     * 设置WebView cookie
     */
    public static void setAppCookie(){
        String serverip = SpUtils.getString(context, Constant.SERVERIP,"");
        String port = SpUtils.getString(context, Constant.PORT,"");

        if(TextUtils.isEmpty(serverip)||TextUtils.isEmpty(port)){
            Toast.makeText(context,"IP地址和端口号为空！",Toast.LENGTH_LONG).show();
            return;
        }

        //http://112.125.95.20:8585/project/
        String url = "http://"+serverip;
        HttpUrl httpUrl = HttpUrl.parse(url);
        CookieStore cookieStore = OkGo.getInstance().getCookieJar().getCookieStore();
        List<Cookie> cookies = cookieStore.getCookie(httpUrl);

        synCookies(context, url, cookies);
    }

    /**
     * 退出登陆时,移除 cookie
     */
    public static void removeAppCookie(){
        String serverip = SpUtils.getString(context, Constant.SERVERIP,"");
        String port = SpUtils.getString(context, Constant.PORT,"");

        if(TextUtils.isEmpty(serverip)||TextUtils.isEmpty(port)){
            Toast.makeText(context,"IP地址和端口号为空！",Toast.LENGTH_LONG).show();
            return;
        }

        //http://112.125.95.20:8585/project/
        String url = "http://"+serverip;
        HttpUrl httpUrl = HttpUrl.parse(url);
        CookieStore cookieStore = OkGo.getInstance().getCookieJar().getCookieStore();
        List<Cookie> cookies = cookieStore.getCookie(httpUrl);

        cookieStore.removeAllCookie();
        synCookies(context, url, cookies);
    }


    /**
     * 同步cookie
     * @param context
     * @param url
     */
    private static void synCookies(Context context, String url, List<Cookie> cookies) {
        CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeSessionCookie();//移除

        for (int i = 0; i < cookies.size(); i++) {
            cookieManager.setCookie(url, cookies.get(i).toString());//cookies是在HttpClient中获得的cookie
        }
        CookieSyncManager.getInstance().sync();
    }

    /**
     * 同步cookie
     * @param context
     * @param url
     */
    private static void synCookies(Context context, String url, String cookie) {
        CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeSessionCookie();//移除
        cookieManager.setCookie(url, cookie);//cookies是在HttpClient中获得的cookie
        CookieSyncManager.getInstance().sync();
    }

}
